<template>
  <div class="rank-song-container">
    <el-card class="rank-song-card">
      <template #header>
        <div class="card-header">
          <span>{{ rankInfo.rankTitle }} - 榜单歌曲管理</span>
          <el-button type="primary" @click="handleAdd">添加歌曲</el-button>
        </div>
      </template>

      <!-- 歌曲列表 -->
      <el-table :data="songList" border stripe v-loading="loading">
        <el-table-column type="selection" width="60" />
        <el-table-column prop="rankSongId" label="榜单歌曲ID" width="120"/>
        <el-table-column prop="songName" label="歌曲名称" />
        <el-table-column prop="singerName" label="歌手" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑歌曲对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form :model="songForm" :rules="songRules" ref="songFormRef" label-width="100px">
        <el-form-item label="歌曲" prop="songId">
          <el-select 
            v-model="songForm.songId" 
            placeholder="请选择歌曲" 
            style="width: 100%"
            filterable
            remote
            :remote-method="searchSongs"
            :loading="songSearchLoading"
          >
            <el-option
              v-for="item in songOptions"
              :key="item.id"
              :label="`${item.songName} - ${item.singerName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSong">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute,onBeforeRouteUpdate } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/services/api'

export default {
  name: 'RankSong',
  setup() {
    const route = useRoute()
    
    // 加载状态
    const loading = ref(false)
    const songSearchLoading = ref(false)
    
    // 排行榜信息
    const rankInfo = ref({
      id: null,
      rankTitle: ''
    })
    
    // 歌曲列表
    const songList = ref([])
    
    // 歌曲搜索选项
    const songOptions = ref([])
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 对话框相关
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)
    
    // 歌曲表单
    const songForm = reactive({
      id: null,
      songId: null,
      rankId: null,
      songName: '',
      singerName: ''
    })
    
    // 表单验证规则
    const songRules = {
      songId: [
        { required: true, message: '请选择歌曲', trigger: 'change' }
      ]
    }
    
    // 表单引用
    const songFormRef = ref(null)
    
    // 获取排行榜信息
    const getRankInfo = async (rankId) => {
      try {
        const response = await api.rank.getById(rankId)
        if (response?.data) {
          rankInfo.value = {
            id: response.data.id || response.data.rankId,
            rankTitle: response.data.rankTitle
          }
          songForm.rankId = rankInfo.value.id
        }
      } catch (error) {
        ElMessage.error('获取排行榜信息失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 获取排行榜歌曲列表
    const getSongList = async () => {
      if (!rankInfo.value.id) return
      
      loading.value = true
      try {
        const response = await api.rankSong.getByRankId(rankInfo.value.id)
        if (response?.data) {
          songList.value = response.data.map(item => ({
            id: item.id || item.rankSongId,
            songId: item.songId,
            rankId: item.rankId,
            songName: item.songName,
            singerName: item.singerName
          }))
          pagination.total = songList.value.length
        }
      } catch (error) {
        ElMessage.error('获取歌曲列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
    
    // 搜索歌曲（用于下拉选择）
    const searchSongs = async (query) => {
      if (!query) {
        songOptions.value = []
        return
      }
      
      songSearchLoading.value = true
      try {
        const response = await api.song.search(query)
        if (response?.data) {
          songOptions.value = response.data.map(item => ({
            id: item.id || item.songId,
            songName: item.name || item.songName,
            singerName: item.singerName
          }))
        }
      } catch (error) {
        ElMessage.error('搜索歌曲失败: ' + (error.message || '未知错误'))
      } finally {
        songSearchLoading.value = false
      }
    }
    
    // 处理添加
    const handleAdd = () => {
      dialogTitle.value = '添加歌曲'
      isEdit.value = false
      // 重置表单
      Object.assign(songForm, {
        id: null,
        songId: null,
        rankId: rankInfo.value.id,
        songName: '',
        singerName: ''
      })
      dialogVisible.value = true
    }
    
    // 处理编辑
    const handleEdit = (row) => {
      dialogTitle.value = '编辑歌曲'
      isEdit.value = true
      // 填充表单数据
      Object.assign(songForm, {
        id: row.id,
        songId: row.songId,
        rankId: row.rankId,
        rankNum: row.rankNum,
        songName: row.songName,
        singerName: row.singerName
      })
      dialogVisible.value = true
    }
    
    // 处理删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要从排行榜中移除歌曲 "${row.songName}" 吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await api.rankSong.delete(row.id)
          if (response?.code === 1) {
            ElMessage.success('删除成功')
            getSongList()
          } else {
            ElMessage.error(response?.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 提交歌曲
    const submitSong = () => {
      songFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            let response
            if (isEdit.value) {
              // 编辑
              response = await api.rankSong.update({
                id: songForm.id,
                songId: songForm.songId,
                rankId: songForm.rankId
              })
            } else {
              // 新增
              response = await api.rankSong.add({
                songId: songForm.songId,
                rankId: songForm.rankId
              })
            }
            
            if (response.code === '1') {
              ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
              dialogVisible.value = false
              await getSongList()
            } else {
              ElMessage.error(response?.msg || (isEdit.value ? '编辑失败' : '添加失败'))
            }
          } catch (error) {
            ElMessage.error((isEdit.value ? '编辑失败' : '添加失败') + ': ' + (error.message || '未知错误'))
          }
        }
      })
    }
    
    // 关闭对话框
    const handleDialogClose = () => {
      songFormRef.value.resetFields()
    }
    
    // 分页相关
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      getSongList()
    }
    
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      getSongList()
    }
    
    // 初始化数据
    const init = async (rankId) => {
      await getRankInfo(rankId)
      await getSongList()
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      const rankId = route.params.id
      if (rankId) {
        init(rankId)
      }
    })
    
    // 路由更新时重新获取数据
    onBeforeRouteUpdate((to) => {
      const rankId = to.params.id
      if (rankId) {
        init(rankId)
      }
    })
    
    return {
      rankInfo,
      loading,
      songSearchLoading,
      songList,
      songOptions,
      pagination,
      dialogVisible,
      dialogTitle,
      songForm,
      songRules,
      songFormRef,
      onBeforeRouteUpdate,
      searchSongs,
      handleAdd,
      handleEdit,
      handleDelete,
      submitSong,
      handleDialogClose,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.rank-song-container {
  padding: 20px;
}

.rank-song-card {
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>